<?php
namespace app\demo_record\utility;

class DBUtility
{
    public function encode($fields)
    {
        foreach($fields as &$field){
            if($field['type'] === "checkbox"){
                $field["value"] = $field["value"] ? 1 : 0 ;
            }
            elseif($field['type'] === "multiple"){
                $field["value"] = implode(",",$field["value"]);
            }
            elseif(in_array($field['type'],["location","files","images"])){
                $field["value"] = json_encode($field["value"],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
            }

            $item=[];
            $extend=[];
            foreach($field as $key => $value){
                if(in_array($key,["name","title","type","value","describe","readable","writable","required"])){
                    $item[$key] = $value;
                }
                else{
                    $extend[$key] = $value;
                }
            }
        }
        return $fields;
    }
    public function decode($fields)
    {
        return $fields;
    }
    /**
     * 内部格式转换成数据库存储格式
     */
    public function convertValues($fields,$values)
    {
        foreach($fields as $field){
            if($field['type'] === "checkbox"){
                $values[$field["name"]] = $values[$field["name"]] ? 1 : 0 ;
            }
            elseif($field['type'] === "multiple"){
                $values[$field["name"]] = implode(",",$values[$field["name"]]);
            }
            elseif(in_array($field['type'],["location","files","images"])){
                $values[$field["name"]] = json_encode($values[$field["name"]],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
            }
        }
        return $values;
    }
    /**
     * 恢复成内部格式
     */
    public function recoverValues($fields,$values)
    {
        foreach($fields as &$field){
            if(in_array($field['type'],["number","range","date","time","datetime"])){
                $values[$field["name"]] = floatval($values[$field["name"]]);
            }
            elseif($field['type'] === "checkbox"){
                $values[$field["name"]] = $values[$field["name"]] !== '0' ;
            }
            elseif($field['type'] === "multiple"){
                $values[$field["name"]] = explode(",",$values[$field["name"]]);
            }
            elseif(in_array($field['type'],["location","files","images"])){
                $values[$field["name"]] = json_decode($values[$field["name"]],true);
            }
        }
        return $values;
    }
}
